import { _decorator, Component, Node } from 'cc';
import { BaseView } from '../../../../../scripts/libs/rxjs/cc3/BaseView';
import { ReactiveProperty } from '../../../../../scripts/libs/rxjs/cc3/ReactiveProperty';
import { IapProductInfo } from '../../../../../scripts/managers/SDK/IapSDKManager';
import { IapButtonItem } from '../../ShopPanel/IapButtonItem';
import { find } from 'cc';
import { Label } from 'cc';
import { i18n } from '../../../../../scripts/i18n';
import { MSResolve, MSRToString_th_m } from '../../../../../scripts/libs/utils/date';
const { ccclass, property } = _decorator;

@ccclass('BundleItem')
export class BundleItem extends BaseView {

    data = ReactiveProperty.Create<IapProductInfo>(null);

    @property(IapButtonItem)
    iapButtonItem: IapButtonItem = null;

    useObserves() {
        return [
            this.data.subscribe(this.refresh.bind(this)),
        ];
    }

    refresh() {
        if (this.data.value == null) return;
        let info = this.data.value;
        let coinLabel = find('board/coin/label', this.node).getComponent(Label);
        coinLabel.string = `x${info.provide.coin ?? 0}`;

        let nameLabel = find('board/name', this.node).getComponent(Label);
        nameLabel.string = i18n.t(`iap.${info.flag}.name`);
        let layoutNode = find('board/Layout', this.node);
        for (let i = 0; i < layoutNode.children.length; i++) {
            let itemNode = layoutNode.children[i];
            if (info.provide[itemNode.name] > 0) {
                itemNode.active = true;
                let valueLabelNode = find('label', itemNode);
                if (valueLabelNode != null) {
                    if (['inf_heart_sec', 'noads_sec'].includes(itemNode.name)) {
                        let msr = MSResolve(info.provide[itemNode.name] * 1000);
                        valueLabelNode.getComponent(Label).string = MSRToString_th_m(msr);
                    } else {
                        valueLabelNode.getComponent(Label).string = `x${info.provide[itemNode.name] ?? 0}`;
                    }
                }
            } else {
                itemNode.active = false;
            }
        }
        let iapButtonItem = find('board/btn', this.node).getComponent(IapButtonItem);
        iapButtonItem.data.value = info;
        // iapButtonItem.successCommand.subscribe(_ => {
        //     this.log('>>>> success command', _);
        // });

        let discountFlag = find('board/flag', this.node);
        let discountLabel = find('board/flag/label', this.node)?.getComponent(Label);
        if (discountLabel != null) {
            if (info.discount > 0) {
                discountFlag.active = true;
                discountLabel.string = `${Math.round((1 - info.discount) * 100)}%\nOFF`;
            } else {
                discountFlag.active = false;
            }
        }
    }
}

